package one.stand.eureka.info;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.concurrent.TimeUnit;

@Slf4j
public class CommandExecuter {

    private static LogWriter logWriter = new LogWriter();

    protected boolean exe(String command, String key) {
        if (StringUtils.isBlank(command)) {
            logWriter.error(key, "command is null");
            throw new RuntimeException("command is null");
        }

        log.info("exec({}) start", command);
        logWriter.command(key, "$ " + command);
        try {
            Process process = Runtime.getRuntime().exec(command);
            printMessage(process.getInputStream(), key);
            printMessage(process.getErrorStream(), key);
//            process.getOutputStream().close();

//            return new BufferedReader(new InputStreamReader(process.getInputStream()));

            boolean value = process.waitFor(1L, TimeUnit.MINUTES);
            log.info("command is {}", value);
//            if (StringUtils.isNoneBlank(key)) {
//                logs.get(key).add("command is " + value);
//            }
            return value;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            logWriter.error(key, "$ " + e.getMessage());
            return false;
        }
    }

    private static void printMessage(final InputStream input, String key) {
        Runnable runnable = new Runnable() {
            private String logKey;

            public Runnable setKey(String key) {
                this.logKey = key;
                return this;
            }

            public void run() {
                try {
                    Reader reader = new InputStreamReader(input, "GBK");
                    BufferedReader bf = new BufferedReader(reader);
                    String line = null;
                    while ((line = bf.readLine()) != null) {
                        log.info("{}: {}", logKey, line);
                        logWriter.info(logKey, line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.setKey(key);
        new Thread(runnable).start();
    }
}
